package com.orangelife.mobile.login.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.jump.LocationJumper;
import com.common.sp.CommSp2;
import com.common.sp.UserSp;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.datatrack.DataTrack;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.thirdsdk.jpush.JPushTagHelper;
import com.orangelife.mobile.app.application.CurryApplication;
import com.thirdsdk.baidu.MyLocationListener;
import com.orangelife.mobile.common.activity.BaseMapActivity;
import com.orangelife.mobile.login.adapter.SelectCityGridAdapter;
import com.orangelife.mobile.login.biz.CommunityHttpBiz;
import com.thirdsdk.zhugeio.ZhugeIOHelper;

import java.util.HashMap;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 选择城市
 * <p/>
 * Create by yw.Modify by wgf on 160427.
 *
 * @author yw
 */
public class SelectCityActivity extends BaseMapActivity implements
        OnClickListener {
    /* 表示查找的图片 */
    private ImageView ivSearch;
    /* 查找的输入框 */
    private EditText etSearch;
    /* 城市列表 */
    private GridView gvCity;
    /* 标题 */
    private TextView tvTitle, tvTitleRight;
    private LinearLayout llTitleLeft;
    private LinearLayout llSearch;
    private RelativeLayout rlLocateCity;
    /* 选择城市的自定义适配器 */
    private SelectCityGridAdapter<Map<String, Object>> adapter;
    /* 定位城市 */
    private TextView tvCity;
    /* 未开通服务城市提示 */
    private TextView tvCityHint;
    private List<Map<String, Object>> list;
    private static final int WHAT_CITY_SEARCH = 1;
    private static final int WHAT_CITY_FROM_LOCATE = 2;
    private Map<String, Object> mapLocation;
    private boolean isFirstLoc = true;
    /** 是否定位成功 */
    private boolean hasLocatedSuccess = false;
    private String back = "";
    private String city = "";

    final  String MODULE_NAME="/app/guidePage/register/selCity";

    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.activity_select_city);
        initView();
        setTitle();
        setListener();
        setAdapter();
        hideCitySearchView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startLocClient();
        registerReceiver(mHandler, WHAT_CITY_FROM_LOCATE);
        requestCityList();
    }

    /**
     * 数据采集体不要删除
     * @return
     */
    public Map<String,Object> getDataTrack(){
        Map<String,Object> map=new HashMap<>();
        map.put("UI_HOST", DataTrack.APP_NAME);
        map.put("UI_PATH", MODULE_NAME);
        return map;
    }

    private void zhugeTrack(String cityName,boolean isLocation) {
        Map<String,Object> map=new HashMap<>();
        map.put("cityName",cityName);
        map.put("isGps",isLocation);
        DataTrack.clickTrack("btnCity",map);
    }

    private void requestCityList() {
        showDialog(this);
        CommunityHttpBiz.requestCityList(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                closeDialog();
                list = CommunityHttpBiz.handleCityList(jsonObject);
                if (list != null) {
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void handleLocateCity(Object obj) {
        if (obj != null) {
            mapLocation = JSONHelper
                    .jsonToMap(String.valueOf(obj));
            if (mapLocation == null) {
                tvCity.setText("定位失败，请选择城市");
                return;
            }
            city = String.valueOf(mapLocation.get("city"));
            if (city.equals("null")) {
                city = "";
            }
            isServiceCity(city);
            tvCity.setText(city);
            if (city.equals("")) {
                /*判断是否是第一次定位 */
                if (isFirstLoc) {
                    isFirstLoc = false;
                    tvCity.setText("定位失败，请选择城市");
                    if (!isConnected()) {
                        openBuilder();
                    }
                }
            }

        } else {
            tvCity.setText("定位失败，请选择城市");
        }
    }

    /** 开启定位 */
    private void startLocClient() {
        if (isFirstLoc && mLocClient != null) {
            mLocClient.start();
        }
    }

    private void stopLocClient() {
        if (mLocClient != null) {
            mLocClient.stop();
        }
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitleRight = (TextView) findViewById(R.id.tv_one);
        llTitleLeft = (LinearLayout) findViewById(R.id.ib_title_left);
        tvCity = (TextView) findViewById(R.id.tv_city);
        tvCityHint = (TextView) findViewById(R.id.tv_city_hint);
        ivSearch = (ImageView) findViewById(R.id.iv_search);
        etSearch = (EditText) findViewById(R.id.et_search_city);
        gvCity = (GridView) findViewById(R.id.gvCities);
        llSearch = (LinearLayout) findViewById(R.id.ll_search);
        rlLocateCity = (RelativeLayout) findViewById(R.id.rlLocateCity);
    }

    private void setAdapter() {
        list = new ArrayList<>();
        adapter = new SelectCityGridAdapter(this, list);
        gvCity.setAdapter(adapter);
    }

    private void setListener() {
        rlLocateCity.setOnClickListener(this);
        ivSearch.setOnClickListener(this);
        gvCity.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                jumpToCommunityFromCityList(position);
            }
        });
    }

    /** 保存定位信息 */
    private void saveLocationInfo(String lon, String lat) {
        CommSp2.setLatitude(lat);
        CommSp2.setLongitude(lon);
    }

    private void setTitle() {
        tvTitle.setText(getResources()
                .getString(R.string.choose_city));
        tvTitleRight.setVisibility(View.GONE);
        Intent data = getIntent();
        if (data != null) {
            back = String.valueOf(data.getStringExtra("back"));
            if ("guide".equals(back)) {
                llTitleLeft.setVisibility(View.GONE);
            }
        }
    }

    private void hideCitySearchView() {/*功能废弃*/
        llSearch.setVisibility(View.GONE);
    }

    /** 从GPS定位的城市，跳转到城市 */
    private void jumpToCommunityFromAutoLocate() {
        String cityName = tvCity.getText().toString();
        if (cityName.equals("定位失败，请选择城市")) {
            ToastHelper.getInstance()._toast("定位失败，请选择城市");
        } else if (!StringUtil.isContainBlank(cityName)) {
            String lon = "";
            String lat = "";
            if (mapLocation != null) {
                lon = String.valueOf(mapLocation.get("lon"));
                lat = String.valueOf(mapLocation.get("lat"));
            }
            jumpToCommunity(cityName, lon, lat, true);
        } else {
            ToastHelper.getInstance().displayToastWithQuickClose(
                    getResources().getString(
                            R.string.failed_position_choose));
        }
    }

    /** 从服务端下载的城市列表，跳转到城市 */
    private void jumpToCommunityFromCityList(int position) {
        //String cityId = String.valueOf(list.get(position).get("cityID"));
        String city = String.valueOf(list.get(position).get("city"));
        String longitude = String.valueOf(list.get(position).get("longitude"));
        String latitude = String.valueOf(list.get(position).get("latitude"));
        jumpToCommunity(city, longitude, latitude, false);
    }

    private void jumpToCommunity(String city, String longitude, String latitude, boolean isLocation) {
        LocationJumper.jumpToSelectComm(this, city, longitude, latitude, isLocation);
        stopLocClient();
        saveLocationInfo(longitude, latitude);
        zhugeTrack(city,isLocation);
        setJPushTag(city);
        UserSp.setCity(city);
    }

    private void setJPushTag(String city) {
        JPushTagHelper.getInstance().setContext(this);
        JPushTagHelper.getInstance().setTag(city);
    }

    @Override
    public MyLocationListener initListener(MyLocationListener myListener) {
        if (!isConnected()) {
            openBuilder();
            return null;
        }
        myListener = new MyLocationListener(this, null, null);
        return myListener;
    }

    /**
     * 弹出提示框
     */
    private void openBuilder() {
        final ConfirmDialog dialog = new ConfirmDialog(SelectCityActivity.this, "温馨提示", getResources().getString(R.string.net_text_prompt), "取消", "确认");
        dialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doLeft() {
                dialog.dismiss();
            }

            @Override
            public void doRight() {
                Intent intent = new Intent();
                intent.setClassName("com.android.settings",
                        "com.android.settings.Settings");
                startActivity(intent);
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    /**
     * 判断定位城市是否为服务城市
     *
     * @param city
     */
    private void isServiceCity(String city) {
        boolean isService = false;
        if (city.equals("") || city.equals("null")) {
            tvCityHint.setVisibility(View.GONE);
        } else {
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    String str = String.valueOf(list.get(i).get("city"));
                    str = str.substring(0, str.length() - 1);
                    if (city.equals(str)) {
                        isService = true;
                        break;
                    } else {
                        isService = false;
                    }
                }
            }
            if (isService) {
                tvCity.setTextColor(getResources().getColor(R.color.text_black));
                tvCityHint.setVisibility(View.INVISIBLE);
            } else {
                tvCity.setTextColor(getResources().getColor(R.color.text_color_gray));
                tvCityHint.setVisibility(View.VISIBLE);
            }
        }


    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            closeDialog();
            switch (msg.what) {
                case WHAT_CITY_FROM_LOCATE:
                    handleLocateCity(msg.obj);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rlLocateCity:
                jumpToCommunityFromAutoLocate();
                break;
            case R.id.iv_search:
                String search = etSearch.getText().toString();
                CommunityHttpBiz.requestCityListByKeyword(search, mHandler, 0);
                break;
            default:
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (back.equals("guide")) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                exit();
            }
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private boolean isExit;
    @SuppressLint("HandlerLeak")
    Handler mHandler2 = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }

    };

    /**
     * 双击退出的方法体
     */
    public void exit() {
        if (!isExit) {
            isExit = true;
            ToastHelper.getInstance()._toast(
                    getResources().getString(
                            R.string.again_according_to_exit_the_program));
            mHandler2.sendEmptyMessageDelayed(0, 2000);
        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            CurryApplication.getInstance().exit();
            this.finish();
        }
    }

    public void hideInput(View v) {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }
}